import React from 'react'
import { Layout,Dropdown,Menu,Avatar } from 'antd';
import {withRouter} from 'react-router-dom';
import {MenuUnfoldOutlined,MenuFoldOutlined,UserOutlined}from '@ant-design/icons'
import {connect}from "react-redux"

//topheader是状态的发送者，引入connect
const {Header} = Layout

function TopHeader(props) {
    const changeCollapsed=()=>{
        props.changeCollapsed();    //调用函数，该函数的返回值将action给store，store给reducer处理。
    }
    const {role:{roleName},username}=JSON.parse(localStorage.getItem("token")) //要把字符对象化，不然拿不到。
    const menu = (
      <Menu>
        <Menu.Item key={1}>
          {roleName}
        </Menu.Item>
        <Menu.Item key={2} danger onClick={()=>{
          localStorage.removeItem("token");
          props.history.replace("/login");
        }}>退出登录</Menu.Item>
        {/* 清除token */}
      </Menu>
    );
    return (
        <Header className="site-layout-background" style={{ padding: "0 16px" }}>
            {
                props.isCollapsed?<MenuUnfoldOutlined onClick={changeCollapsed}/>:<MenuFoldOutlined onClick={changeCollapsed}/>
            }
            <div style={{ float: "right" }}>
            <span>欢迎<span style={{color:"#1890ff"}}>{username}</span>回来</span>
              <Dropdown overlay={menu}>
                  <Avatar size="large" icon={<UserOutlined />} />
              </Dropdown>
            </div>
          </Header>
    )
}
/*
*  connect(
*   mapStateToProps    state到props的映射
*   mapDispatchToProps
* )()
* */
const mapStateToProps = (state) => {
    const {collApsed:{isCollapsed}}=state
    //  collApsed: {isCollapsed: false}   state 就是reducer返回的状态
  return{
      isCollapsed
  }
}
const mapDispatchToProps  = {
     changeCollapsed(){
         return{
             type:"change_collapsed"
         }
     }
}
export default connect(mapStateToProps,mapDispatchToProps)(withRouter(TopHeader));